package com.hd.trans.share;



import static com.hd.trans.share.SRTUtils.KEY_END_LINE;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * srt文件 工具类
 */
public final class SRTParser {
    private SRTParser() {
    }

    private static final String TAG = "hd/SRTParser";

    private static final Pattern PATTERN_TIME = Pattern.compile("([\\d]{2}:[\\d]{2}:[\\d]{2},[\\d]{3}).*([\\d]{2}:[\\d]{2}:[\\d]{2},[\\d]{3})");
    private static final Pattern PATTERN_NUMBERS = Pattern.compile("(\\d+)");
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");


    @NonNull
    public static ArrayList<Subtitle> getSubtitlesFromFile(String path) {
        return getSubtitlesFromFile(path, false, false);
    }

    @NonNull
    public static ArrayList<Subtitle> getSubtitlesFromFile(String path, boolean addSegment) {
        return getSubtitlesFromFile(path, addSegment, false);
    }

    /**
     * @param path
     * @param addSegment 添加分段
     * @param usingNodes
     * @return
     */
    @NonNull
    public static ArrayList<Subtitle> getSubtitlesFromFile(String path, boolean addSegment, boolean usingNodes) {
        if (path == null)
            return new ArrayList<>();
        Log.d(TAG, "getSubtitlesFromFile " + path + " addSegment:" + addSegment);
        ArrayList<Subtitle> subtitles = new ArrayList<>();
        Subtitle sub = null;
        StringBuilder stringBuilder = null;
        int cacheLength = 0;

        Subtitle cacheSubTitle = null;
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)), DEFAULT_CHARSET));) {
            sub = new Subtitle();
            stringBuilder = new StringBuilder();

            while (br.ready()) {
                // 读取数据
                String line = br.readLine();
                // srt id
                Matcher matcher = PATTERN_NUMBERS.matcher(line);

                if (matcher.find()) {
                    // srt id
                    sub.id = Integer.parseInt(matcher.group(1));
                    line = br.readLine();
                }
                // srt 时间
                matcher = PATTERN_TIME.matcher(line);

                if (matcher.find()) {
                    // start time
                    sub.startTime = matcher.group(1);
                    sub.timeIn = SRTUtils.textTimeToMillis(sub.startTime);
                    // end time
                    sub.endTime = matcher.group(2);
                    sub.timeOut = SRTUtils.textTimeToMillis(sub.endTime);
                }

                // srt 内容
                // 清理 stringBuilder内容
                stringBuilder.setLength(0);
                String aux = "";
                while ((aux = br.readLine()) != null && !aux.isEmpty()) {
                    stringBuilder.append(aux);
                }

                line = stringBuilder.toString();
                line = line.replaceAll(KEY_END_LINE, "\n");

                // 智能分段
                if (addSegment) {
                    boolean needAdd = false;
                    // 5s停顿判断
                    if (cacheSubTitle != null && sub.timeIn > cacheSubTitle.timeOut && (sub.timeIn - cacheSubTitle.timeOut > 5000)) {
                        needAdd = true;
                    }
                    Log.d(TAG, "getSubtitlesFromFile  3s停顿判断:" + needAdd);

                    // 100字句号判断
                    if (!needAdd) {
                        int length = getTextLength(line);
                        cacheLength = cacheLength + length;
                        // 100 字智能分段
                        if (cacheLength >= 100 && isEndChar(line)) {
                            needAdd = true;
                        }
                    }
                    Log.d(TAG, "getSubtitlesFromFile  100字句号判断:" + needAdd);

                    if (needAdd) {
                        if (!line.endsWith("\n\n")) {
                            if (line.endsWith("\n")) {
                                line = line + "\n";
                            } else {
                                line = line + "\n\n";
                            }
                        }
                        cacheLength = 0;
                    }
                    cacheSubTitle = sub;
                }
                sub.text = line;
                sub.textLength = getTextLength(line);
                subtitles.add(sub);

                if (usingNodes) {
                    sub.nextSubtitle = new Subtitle();
                    sub = sub.nextSubtitle;
                } else {
                    sub = new Subtitle();
                }
            }
        } catch (Exception e) {
            Log.e("hd/", "error parsing srt file:" + e.getMessage());
        }
        return subtitles;
    }


    public static boolean isEndChar(String string) {
        return (string.endsWith("。") || string.endsWith("。\n")
                || string.endsWith(".") || string.endsWith(".\n")
                || string.endsWith("?") || string.endsWith("?\n")
                || string.endsWith("？") || string.endsWith("？\n")
                || string.endsWith("!") || string.endsWith("!\n")
                || string.endsWith("！") || string.endsWith("！\n"));
    }

    private static int getTextLength(String text) {
        if (text == null || TextUtils.isEmpty(text)) {
            return 0;
        } else {
            return text.length();
        }
    }

}
